# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging,sys,threading

if sys.hexversion > 0x030000F0:
    from xmlrpc.server import SimpleXMLRPCServer
    from xmlrpc.server import SimpleXMLRPCRequestHandler
else:
    from SimpleXMLRPCServer import SimpleXMLRPCServer
    from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler

from piHAlibs import (addr2host)

logger = logging.getLogger()


class XMLRPCHandler(SimpleXMLRPCRequestHandler):
	rpc_paths = ('/RPC2',)
		

class RPCServer(SimpleXMLRPCServer):
    def __init__(self,addr=None):
        self.host,self.port = addr2host(defaddr=('localhost','8000'),addr=addr)
        self.requestHandler = XMLRPCHandler
        self.name = 'RPCServer'
        self.Functions = []
        self.type = 'SRV'
        self.servercmds = {'STARTS':self.starts,'STOPS':self.stops}

    def register(self):
        self.register_introspection_functions()
        for f in self.Functions:
            self.register_function(f[0],f[1])

    def tsetup(self):
        SimpleXMLRPCServer.__init__(self, (self.host, self.port), self.requestHandler)
        self.register()
        self.setup = True

    def serve(self):
        print ('Listening at address %s on port number %s...\n' % (self.host, self.port))
        self.serve_forever()
 
    def starts(self):
        tt = threading.Thread(target=self.serve)
        tt.name = 'RPCServer_' + self.name
        tt.daemon = True
        tt.start()
        print ('RPCServer %s started and active...' % self.name)

    def stops(self):
        self.shutdown()
        print ('RPCServer %s shutting down...' % self.name)

